<template>
    <div>
        <el-card shadow="hover" style="text-align: left;">
            <el-breadcrumb separator-class="el-icon-arrow-right">
                <el-breadcrumb-item :to="{ path: '/' }">首页</el-breadcrumb-item>
                <el-breadcrumb-item >学生管理</el-breadcrumb-item>
                <el-breadcrumb-item :to="{ path: '/student/list' }">学生列表</el-breadcrumb-item>
            </el-breadcrumb>
           <!--1. 条件查询带分页-->
            <el-form :inline="true" :model="studentSearch" class="demo-form-inline" >
                <el-form-item >
                    <el-input v-model="studentSearch.sname" placeholder="学生姓名" size="medium"></el-input>
                </el-form-item>
                <el-form-item >
                    <el-input v-model="studentSearch.addr" placeholder="学生住址" size="medium"></el-input>
                </el-form-item>
                <el-form-item >
                    <el-select v-model="studentSearch.cid" placeholder="选择所在班级" size="medium">
                        <el-option label="所有班级" value="0"></el-option>
                        <el-option :label="c.cname" :value="c.cid" v-for="c in classes" :key="c.cid"></el-option>
                    </el-select>
                </el-form-item>
                <el-form-item>
                    <el-button type="primary" @click="search" size="medium"  icon="el-icon-search" plain>查询</el-button>
                </el-form-item>
                <el-form-item>
                    <el-button type="success" @click="addStud" size="medium"  icon="el-icon-plus" plain>添加</el-button>
                </el-form-item>
            </el-form>

            <!--2. 表格展示数据-->
            <el-table
                    :data="students"
                    style="width: 100%">
                <el-table-column
                        label="学号"
                        prop="sid"
                        align="center"
                        width="180">
                </el-table-column>
                <el-table-column
                        label="姓名"
                        align="center"
                        prop="sname">
                </el-table-column>
                <el-table-column
                        label="性别"
                        align="center"
                        prop="sex">
                </el-table-column>
                <el-table-column
                        label="年龄"
                        align="center"
                        prop="age">
                </el-table-column>
                <el-table-column
                        label="住址"
                        align="center"
                        prop="addr">
                </el-table-column>
                <el-table-column
                        label="所在班级"
                        align="center"
                        prop="cname">
                </el-table-column>
                <el-table-column label="操作" align="center">
                    <template slot-scope="scope">
                        <el-button-group>
                        <el-button
                                size="mini"
                                type="primary"
                                @click="handleEdit(scope.$index, scope.row)" icon="el-icon-edit"></el-button>
                        <el-button
                                size="mini"
                                type="danger"
                                @click="handleDelete(scope.$index, scope.row)" icon="el-icon-delete"></el-button>
                        </el-button-group>
                    </template>
                </el-table-column>
            </el-table>
            <!--3. 分页导航-->
            <el-pagination
                    @size-change="handleSizeChange"
                    @current-change="handleCurrentChange"
                    :current-page="page"
                    :page-sizes="[3, 6, 9, 12]"
                    :page-size="pageSize"
                    layout="total, sizes, prev, pager, next, jumper"
                    :total="total">
            </el-pagination>
            <!--4. 编辑、添加学生对话框-->
            <el-dialog :title="student.sid ? '修改学生' : '添加学生'"
                       :close-on-click-modal="false"
                       :visible.sync="dialogFormVisible">
                {{student}}
                <el-form :model="student" :rules="rules" ref="ruleForm">
                    <el-form-item label="学生姓名" :label-width="formLabelWidth" prop="sname">
                        <el-input v-model="student.sname" autocomplete="off"></el-input>
                    </el-form-item>
                    <el-form-item label="学生性别" :label-width="formLabelWidth" prop="sex">
                        <el-radio v-model="student.sex" label="男">男</el-radio>
                        <el-radio v-model="student.sex" label="女">女</el-radio>
                    </el-form-item>
                    <el-form-item label="学生年龄" :label-width="formLabelWidth" prop="age">
                        <el-input v-model.number="student.age" autocomplete="off"></el-input>
                    </el-form-item>
                    <el-form-item label="学生住址" :label-width="formLabelWidth" prop="addr">
                        <el-input v-model="student.addr" autocomplete="off"></el-input>
                    </el-form-item>

                    <el-form-item label="所在班级" :label-width="formLabelWidth" prop="cid">
                        <el-select v-model="student.cid" placeholder="请选择所在班级">
                            <el-option :label="c.cname" :value="c.cid" v-for="c in classes"></el-option>
                        </el-select>
                    </el-form-item>
                </el-form>
                <div slot="footer" class="dialog-footer">
                    <el-button @click="dialogFormVisible = false">取 消</el-button>
                    <el-button type="primary" @click="save">确 定</el-button>
                </div>
            </el-dialog>
        </el-card>
    </div>
</template>

<script>
    import {findStudents,search,editStudent} from "@/api/student";
    import {findClasses} from "@/api/classes";

    export default {
        data() {
            // 自定义年龄的验证规则
            let ageValidator = (rule,value,callback)=>{
                if(!value){
                     callback(new Error('年龄不能为空！'))
                }else if(!Number.isInteger(value)){
                     callback(new Error('年龄必须为整数！'))
                }else if(value < 1 || value > 200){
                     callback(new Error('年龄必须在1-200之间！'))
                }else{
                     callback()
                }
            }
            return {
               page:1,              // 当前页
               pageSize:3,          // 每页大小
               total:100,           // 总记录数
               students: [],        // 代表所有学生
               studentSearch:{},    // 当前查询的哪个学生对象
               classes:[],         // 班级列表
               dialogFormVisible:false,  // 对话框的显示与隐藏 true: 显示 false: 隐藏
               student:{},          // 添加或修改学生表单所绑定的对象
               formLabelWidth:'100px',
               rules:{
                   sname:[
                       {required:true,message:'请输入学生姓名',trigger:'blur'}
                   ],
                   sex:[
                       {required: true,message:'请选择性别！',trigger: 'change'}
                   ],
                   age:[
                       {validator: ageValidator,trigger:'blur'}
                   ],
                   addr:[
                       {required:true,message:'请输入住址！',trigger:'blur'}
                   ],
                   cid:[
                       {required:true,message:'请选择班级！',trigger:'change'}
                   ],
               }
            };
        },
        created() {
            //1. 查询所有学生
            // this.findAllStudents()
            this.search()
            //2. 查询所有班级
            this.findClasses()
        },
        methods: {
            //1. 页大小改变时触发（pageSize改变）
            handleSizeChange(val) {
                this.pageSize = val
                this.search()
                console.log(`每页 ${val} 条`);
            },
            //2. 当前页改变时触发（page改变）
            handleCurrentChange(val) {
                this.page = val;
                this.search()
                console.log(`当前页: ${val}`);
            },
            //3. 修改学生
            handleEdit(index, row) {
               //3.1 将当前要修改的学生数据赋值给student对象
               this.student = row
               //3.2 打开对话框
               this.dialogFormVisible = true
            },
            //4. 删除学生
            handleDelete(index, row) {
                this.$confirm(`是否真的要删除学生[${row.sname}], 是否继续?`, '温馨提示', {
                    confirmButtonText: '确定',
                    cancelButtonText: '取消',
                    type: 'warning'
                }).then(() => {
                    let _this = this
                    //4.1 当我们点击了‘确定’按钮后，发送异步请求
                    this.$axios.get(`/student?cmd=delete&sid=${row.sid}`).then(({data})=>{
                       if(data.code === 20000){
                           this.$message({
                               type: 'success',
                               message: data.message,
                               onClose(){
                                   _this.search()
                               }
                           });
                       }
                    })

                }).catch(() => {
                    this.$message({
                        type: 'info',
                        message: '已取消删除'
                    });
                })
            },
            //5. 查询所有学生
            findAllStudents(){
                this.$axios.get("/student?cmd=list").then(({data})=>{
                    console.log("data:",data.data)
                    this.students = data.data.students
                })
            },
            //6. 查询所有班级
            async findClasses(){
                // this.$axios.get("/classes?cmd=list").then(({data})=>{
                //     console.log("data:",data.data)
                //     this.classes = data.data.classes
                // })
                 const {data} = await findClasses();
                 this.classes = data.data.classes
                 console.log("data:::",data)
            },
            //7. 分页带条件查询
            async search(){
                //版本一：(在方法前不需要加async参数)
                // this.$axios.post(`/student?cmd=search&page=${this.page}&pageSize=${this.pageSize}`,"stud="+JSON.stringify(this.studentSearch)).then(({data})=>{
                //     console.log("data:",data)
                //     //7.1 将pr.rows赋值
                //     if(data.code === 20000){
                //         this.students = data.data.pr.rows
                //         this.total = data.data.pr.total
                //     }
                // })
                //版本二：(在方法前不需要加async参数)
                // search(`/student?cmd=search&page=${this.page}&pageSize=${this.pageSize}`,"stud="+JSON.stringify(this.studentSearch)).then(({data})=>{
                //     console.log("data:",data)
                //     //7.1 将pr.rows赋值
                //     if(data.code === 20000){
                //         this.students = data.data.pr.rows
                //         this.total = data.data.pr.total
                //     }
                // })
                //版本三：(在方法前需要加async参数)
                const {data} = await search(`/student?cmd=search&page=${this.page}&pageSize=${this.pageSize}`,"stud="+JSON.stringify(this.studentSearch))
                if(data.code === 20000){
                    this.students = data.data.pr.rows
                    this.total = data.data.pr.total
                }
            },
            //8. 添加学生（界面）
            addStud(){
                //8.1 清空学生对象
                this.student = {}
                //8.2 打开对话框
                this.dialogFormVisible = true
            },
            //9. 保存学生（添加、修改）
             save(){
                //9.1 确定是添加还是修改
                let url = '/student?cmd=add'
                if(this.student.sid){
                    url = '/student?cmd=update'
                }
                //9.2 准备开始操作
                 this.$refs['ruleForm'].validate(async (valid)=>{
                    //9.2.1 此时证明表单中的所有控件都验证通过
                    if(valid){
                        console.log("验证通过！")
                        let _this = this
                        //版本一：（不需要写成：async (valid)）
                        // this.$axios.post(url,'stud='+JSON.stringify(this.student)).then(({data})=>{
                        //     console.log('data:',data)
                        //     if(data.code === 20000){
                        //         this.$message({
                        //             message: data.message,
                        //             type: 'success',
                        //             onClose(){
                        //                 //1. 刷新页面
                        //                 _this.search()
                        //                 //2. 当消息框关闭时，就会自动执行此函数，从而关闭对话框
                        //                 _this.dialogFormVisible = false
                        //             }
                        //         });
                        //     }
                        // })
                        //版本二：（需要写成：async (valid)）
                       const {data} = await editStudent(url,'stud='+JSON.stringify(this.student))
                       if(data.code === 20000){
                           this.$message({
                               message: data.message,
                               type: 'success',
                               onClose(){
                                   //1. 刷新页面
                                   _this.search()
                                   //2. 当消息框关闭时，就会自动执行此函数，从而关闭对话框
                                   _this.dialogFormVisible = false
                               }
                           });
                       }
                    }
                    return false
                })
            }
        },
    }
</script>

<style scoped>
    .el-pagination{
        text-align: right;
        margin-top: 20px;
    }
    .el-breadcrumb{
        margin-top: 5px;
        margin-bottom: 15px;
    }
</style>